package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

type UploadController struct {
	beego.Controller
}

func (u *UploadController) Upload() {
	file, size, err := u.GetFile("upload")
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件接收失败",
		}
		u.ServeJSON()
		return
	}
	defer file.Close()
	if size.Size > 1024*1024*20 {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "文件过大",
		}
		u.ServeJSON()
		return
	}
	//todo: 规定上传视频格式
	video := []string{"png", "jpg", "gif", "GIF", "PNG", "JPG", "mp4"}
	//todo: 截取上传视频后缀
	sux := strings.Split(size.Filename, ".")
	videoSux := sux[1]
	//todo: 判断
	if !strings.Contains(strings.Join(video, "."), videoSux) {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "上传文件格式错误",
		}
		u.ServeJSON()
		return
	}
	//todo: 生成名字
	video_name := strconv.Itoa(int(time.Now().Unix())) + "." + videoSux
	src := "./static/video/" + video_name
	//todo: 打开文件  复制文件
	openFile, err := os.OpenFile(src, os.O_CREATE|os.O_WRONLY, 0777)
	log.Println(err, "111")
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "打开文件失败",
		}
		u.ServeJSON()
		return
	}
	_, err = io.Copy(openFile, file)
	if err != nil {
		u.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "上传视频失败",
		}
		u.ServeJSON()
		return
	}
	//todo: 上传阿里云
	//conmon.Upload(src)
	u.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "上传视频成功",
	}
	u.ServeJSON()
}
